package com.ruoyi.web.controller.common;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.code.kaptcha.Producer;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.common.utils.uuid.IdUtils;

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@RestController
public class CaptchaController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    /**
     * 验证码类型：验证码类型 math 数组计算 char 字符验证
     */
    @Value("${ruoyi.captchaType}")
    private String captchaType;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException {
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        // 作为校验的验证码  captcha_codes: + uuid
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;

        // 初始化图像流（awt模块下的）
        BufferedImage image = null;

        /**
         * Create an image which will have written a distorted text.
         * 建将写入扭曲文本的图像
         * import java.awt.image.BufferedImage;
         * com.ruoyi.framework.config.CaptchaConfig（里面包括了验证码的样式） 重写上面的Bean
         */
        // 生成验证码 == 数学运算模式
        if (Constants.CAPTCHA_TYPE_MATH.equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            // 生成指定的内容 == capText（要绘制的文本） capStr = 3+4=?@7
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            // (结果) code = 7
            code = capText.substring(capText.lastIndexOf("@") + 1);
            // 转换成图片
            image = captchaProducerMath.createImage(capStr);
            // 字符模式
        } else if (Constants.CAPTCHA_TYPE_CHAR.equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }
        // 将验证码 captcha_codes: + uuid  和  code 放入到redis中，并设置过期时间
        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            // 以jpg模式写出
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }

        // 返回给前端
        AjaxResult ajax = AjaxResult.success();
        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }
}
